﻿package com.projects.xenia.documents_activities;

import java.util.ArrayList;
import java.util.HashMap;

import com.projects.xenia.MainGoodsCatalogActivity;
import com.projects.xenia.R;

import com.projects.xenia.add_activities.Activity_Offers;
import com.projects.xenia.documents_classes.Documents_Order;
import com.projects.xenia.documents_classes.Documents_Order.DocLine;
import com.projects.xenia.global_modules.MainGlobalModule;
import com.projects.xenia.prompts_activities.Activity_OrderGoodsPrompt;
import com.projects.xenia.ref_classes.GoodRefObject;
import com.projects.xenia.ref_classes.GoodsRefItem;
import com.projects.xenia.ref_classes.SalesRefItem;

import android.app.Activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

public class Activity_OrderList extends Activity{
	
	private Documents_Order DocumentClass;
	private ArrayList <GoodsRefItem> GoodsRef;
	
	private final int IDR_OrderGoodsPromptSelect = 1;
	private final int IDR_GoodsSelect = 2;
	private final int IDR_OffersSelect = 3;
	
	public HashMap<String, SalesRefItem> OrderSalesCollection;	
	public HashMap<String, GoodsRefItem> OrderAssortmentCollection;
	public HashMap<String, GoodsRefItem> CustomerAssortmentCollection;
	public HashMap<String, DocLine> OrderDocLineCollection;
	
	private EfficientAdapter CurrentAdap;
	private ListView CurrentList;
	
	private TabHost tabs;
	private Context Ctx;	
	
	private ImageView BackwardButton;
	private ImageView GoodsOpenButton;
	private ImageView OffersSelectOpenButton;
	
	private TextView RestSumLabel;
	private TextView OrderSumLabel;	

	private ArrayList <String> OffersGoodsList;
	
	private OnClickListener BackwardButton_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {	
			
			Animation animation = AnimationUtils.loadAnimation(Ctx, R.anim.anim_alpha); 
			v.startAnimation(animation);
			
			finish ();			
		}
	};

	
	private OnClickListener GoodsOpenButton_Click = new OnClickListener() {		
		@Override
		public void onClick(View v) {	
			
			Animation animation = AnimationUtils.loadAnimation(Ctx, R.anim.anim_alpha); 
			v.startAnimation(animation);
			
			Intent GoodsCatalog = new Intent();
			GoodsCatalog.setClass(Ctx,MainGoodsCatalogActivity.class);
			GoodsCatalog.putExtra("DocType",  MainGlobalModule.DocumentsType.Order);
			GoodsCatalog.putExtra("DocId",  DocumentClass.Head.id);
			GoodsCatalog.putExtra("Firm",  DocumentClass.Head.firms_id);
			GoodsCatalog.putExtra("AccType",  DocumentClass.Head.acctype);
			GoodsCatalog.putExtra("Department",  DocumentClass.Head.departments_id);
			GoodsCatalog.putExtra("DocSelection",  01);
			GoodsCatalog.putExtra("SelectOnce",  false);			
			startActivityForResult(GoodsCatalog, IDR_GoodsSelect);
			
		}
	};
	
	private OnLongClickListener GoodsOpenButton_LongClick = new OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {
			
			Animation animation = AnimationUtils.loadAnimation(Ctx, R.anim.anim_alpha); 
			v.startAnimation(animation);
			
			Intent GoodsCatalog = new Intent();
			GoodsCatalog.setClass(Ctx,MainGoodsCatalogActivity.class);
			GoodsCatalog.putExtra("DocType",  MainGlobalModule.DocumentsType.Order);
			GoodsCatalog.putExtra("DocId",  DocumentClass.Head.id);
			GoodsCatalog.putExtra("Firm",  DocumentClass.Head.firms_id);
			GoodsCatalog.putExtra("AccType",  DocumentClass.Head.acctype);
			GoodsCatalog.putExtra("Department",  DocumentClass.Head.departments_id);
			GoodsCatalog.putExtra("DocSelection",  01);
			GoodsCatalog.putExtra("SelectOnce",  true);			
			startActivityForResult(GoodsCatalog, IDR_GoodsSelect);
			
			return true;
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	
		Ctx = this;
	
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.order_content_form);
		
		OffersGoodsList = MainGlobalModule.GetOffersAssortmentsList ();
		 
		BackwardButton = (ImageView)findViewById(R.id._backward);
		BackwardButton.setOnClickListener(BackwardButton_Click);
		
		GoodsOpenButton = (ImageView)findViewById(R.id.GoodsSelectOpen);
		GoodsOpenButton.setOnClickListener(GoodsOpenButton_Click);
		GoodsOpenButton.setOnLongClickListener(GoodsOpenButton_LongClick);	

		
		OffersSelectOpenButton = (ImageView)findViewById(R.id.OffersSelectOpen);		
		OffersSelectOpenButton.setOnClickListener(OffersSelectOpen_Click);
		
		RestSumLabel = (TextView)findViewById(R.id.RestSumLabel);
		OrderSumLabel = (TextView)findViewById(R.id.OrdSumLabel);
		
		DocumentClass = (Documents_Order)MainGlobalModule.DocumentClass;
		
		GoodsRef = MainGlobalModule.GoodsRef;		
		 
		
		tabs = (TabHost) findViewById(android.R.id.tabhost);

		tabs.setup();

		TabHost.TabSpec spec;				

		spec = tabs.newTabSpec("tag3");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Остатки");
		tabs.addTab(spec);		
		
		spec = tabs.newTabSpec("tag1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Заказ/Остатки");
		tabs.addTab(spec);
		
		spec = tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Заказ");
		tabs.addTab(spec);		
		
		spec = tabs.newTabSpec("tag4");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Недос.");
		tabs.addTab(spec);		
		
		//spec = tabs.newTabSpec("tag5");
		//spec.setContent(R.id.tab1);
		//spec.setIndicator("Бонус");
		//tabs.addTab(spec);		
				
		OrderSalesCollection = DocumentClass.SalesCollection;
		OrderAssortmentCollection = DocumentClass.OrderAssortmentCollection;
		CustomerAssortmentCollection = DocumentClass.CustomerAssortmentCollection;
		OrderDocLineCollection = DocumentClass.DocLineCollection;
		
		OffersGoodsList = DocumentClass.OffersGoodsList;
		
		
		CurrentList = (ListView)findViewById(R.id.tablist1);
		CurrentList.setOnItemClickListener(ListItemClick);
		
		CurrentAdap = new EfficientAdapter(Ctx);		
		CurrentList.setAdapter(CurrentAdap);
		
		
		
		tabs.setOnTabChangedListener(TabChange_Click);		
		tabs.setCurrentTab(2);
		
		
	}
	
	
	
	private OnClickListener OffersSelectOpen_Click  = new OnClickListener() {		
		@Override
		public void onClick(View v) {
	
			Animation animation = AnimationUtils.loadAnimation(Ctx, R.anim.anim_alpha); 
			v.startAnimation(animation);
			
			Intent OffersActivity = new Intent ();				 
			OffersActivity.setClass(Ctx,Activity_Offers.class);							 
			startActivityForResult(OffersActivity, IDR_OffersSelect);
			
		}
	};
	
	private void RefreshSumLabels () {
	
		if (DocumentClass.Head.total_restsum > 0)
		{
			RestSumLabel.setText(String.format("Сум.ост: %.2f", DocumentClass.Head.total_restsum));
		}
		else
		{
			RestSumLabel.setText("");
		}
		
		if (DocumentClass.Head.total_ordersum > 0)
		{
			OrderSumLabel.setText(String.format("Сум.зак: %.2f", DocumentClass.Head.total_ordersum));
		}
		else
		{
			OrderSumLabel.setText("");
		}
		
	}
		
	private OnItemClickListener ListItemClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {		
			
			if (MainGlobalModule.ExistsOffersByGoodsId ( ((Documents_Order)DocumentClass).Head.id,GoodsRef.get(position).id)) {					
				
				Toast.makeText(Ctx, "Товар использован в акции, используйте подбор по акции !", Toast.LENGTH_LONG).show();
				
			}
			else
			{

				Intent OrderPrompt = new Intent ();				 
				OrderPrompt.setClass(Ctx,Activity_OrderGoodsPrompt.class);
				OrderPrompt.putExtra("GoodsRefPosition", position);				 
				startActivityForResult(OrderPrompt, IDR_OrderGoodsPromptSelect);
			}
			
			
			
		}	
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		 switch(requestCode) {
		 
		    case IDR_OrderGoodsPromptSelect:
		    	
		    	GetGoodsRefCursorByDoc ();		    	
		    	
		    	int SelPos = data.getIntExtra("GoodsRefPosition",0);		    	
		    	if (SelPos>=CurrentAdap.getCount()) {
		    		CurrentList.setSelection(0);
		    	}
		    	else
		    	{
		    		CurrentList.setSelection(SelPos);	
		    	}		    				    	 
		    	break;		  
		    	
		    case IDR_GoodsSelect:
		    	
		    	GetGoodsRefCursorByDoc ();		    	
		    	
		    	break;
		    	
		    case IDR_OffersSelect:
		    	
		    	GetGoodsRefCursorByDoc ();		    	
	    		
		 }
	    	
	};
	
	
	private OnTabChangeListener TabChange_Click = new OnTabChangeListener() {		
		@Override
		public void onTabChanged(String tabId) {						
			
			GetGoodsRefCursorByDoc ();			
			
		}
	};
	
	private void GetGoodsRefCursorByDoc () {
	
					
		
		String restjoin_condition = "LEFT outer JOIN";
		String order_condition = "";
		String restjoin_restcondition = "";
		
		if (tabs.getCurrentTabTag().equals("tag2")) {
			order_condition = "and o.ordervalue > 0";
		}
		
		if (tabs.getCurrentTabTag().equals("tag3")) {
			order_condition = "and o.restvalue > 0";
		}
		
		if (tabs.getCurrentTabTag().equals("tag4")) {			
			restjoin_condition = "INNER JOIN";
			restjoin_restcondition = "and r.restvalue <=0";
		}		
		
		
		GoodsRef.clear();
		
		try {
			
			Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery(String.format("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,o.price,r.restvalue,g.measure_base,m.descr,gm.mul FROM xdoc_orders_t o inner join xref_goods g on o.goods_id = g.id and o.hdoc_id = ? %s %s xref_goodsrests r ON o.goods_id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? %s left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id ORDER BY o.lineno", order_condition,restjoin_condition,restjoin_restcondition), new String[] {DocumentClass.Head.id,DocumentClass.Head.firms_id,DocumentClass.Head.acctype,DocumentClass.Head.departments_id});		

			if (GoodsCursor.getCount() > 0){
				
				GoodsCursor.moveToFirst();				
				while (GoodsCursor.isAfterLast()==false) {				
					GoodsRefItem gi = new GoodsRefItem ();
					gi.id = GoodsCursor.getString(0);
					gi.parentid = GoodsCursor.getString(1);
					gi.article = GoodsCursor.getString(2);
					gi.descr = GoodsCursor.getString(3);
					gi.isfolder = GoodsCursor.getInt(4);
					gi.weight = GoodsCursor.getDouble(5);
					gi.volume = GoodsCursor.getDouble(6);
					gi.minimum_order = GoodsCursor.getDouble(7);
					gi.price = GoodsCursor.getDouble(8); 
					gi.rest  = GoodsCursor.getDouble(9);				
					gi.measure_base_id  = GoodsCursor.getString(10);				
					gi.measure_base_descr = GoodsCursor.getString(11);
					gi.measure_base_factor = GoodsCursor.getDouble(12);
					gi.position = GoodsRef.size(); 
					GoodsRef.add(gi);
					GoodsCursor.moveToNext();
				}
				GoodsCursor.close();
			}
	
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
		CurrentAdap.notifyDataSetChanged();
		RefreshSumLabels ();
		
		
	}

	public class EfficientAdapter extends BaseAdapter  {
		
		private LayoutInflater mInflater;
		public Context context;
		
		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}
				 
		public View getView(final int position, View convertView, ViewGroup parent) {	
			
			ViewHolder holder;
			
			boolean TOPAssortment = false;
			boolean CustomerAssortment = false;			
		
			if (convertView == null) {			
				convertView = mInflater.inflate(R.layout.order_content_list, null);
			}
			
			holder = new ViewHolder();		
			
			holder.GoodsDescr = (TextView) convertView.findViewById(R.id.OrderGoodTextView);
						
			holder.DocPrice = (TextView) convertView.findViewById(R.id.OrderPriceTextView);
			
			holder.DocRestMeasure  = (TextView) convertView.findViewById(R.id.OrderRestMeasureTextView);
			holder.DocOrderMeasure  = (TextView) convertView.findViewById(R.id.OrderMeasureTextView);			
			
			holder.DocRest = (TextView) convertView.findViewById(R.id.OrderRestTextView);
			holder.DocOrder = (TextView) convertView.findViewById(R.id.OrderCountTextView);
			
			holder.DocRestSum = (TextView) convertView.findViewById(R.id.OrderResRSumTextView);
			holder.DocOrderSum = (TextView) convertView.findViewById(R.id.OrderSumTextView);			
				
			holder.OrdeGoodAddtextView = (TextView) convertView.findViewById(R.id.OrdeGoodAddtextView);
			
			GoodsRefItem gi = getItem(position);
			
			holder.GoodsDescr.setTextColor(Color.WHITE);
			
			SalesRefItem SalesItem = OrderSalesCollection.get(gi.id);
			TOPAssortment = OrderAssortmentCollection.containsKey(gi.id);
			CustomerAssortment = CustomerAssortmentCollection.containsKey(gi.id);			
			Documents_Order.DocLine DocLine = OrderDocLineCollection.get(gi.id);
			
			holder.GoodsDescr.setText(DocLine.goods_descr);
			holder.DocRestMeasure.setText(String.format(" %s(%.1f) ", gi.measure_base_descr,gi.measure_base_factor));
			holder.DocOrderMeasure.setText(String.format(" %s(%.1f) ", DocLine.goods_measures_descr,DocLine.factor));
			
			holder.DocPrice.setText("ц.".concat(String.format("%.2f",DocLine.price*DocLine.factor)));
				
			if (SalesItem!=null){
				holder.GoodsDescr.setTextColor(Color.YELLOW);
			}	
					
			if (DocLine.restvalue > 0) {
				holder.DocRest.setText(String.valueOf(DocLine.restvalue));
				holder.DocRestSum.setText(String.format("=%.2f ", DocLine.rest_sum));
			}
			else
			{
				holder.DocRest.setText("");		
				holder.DocRestSum.setText("");
				holder.DocRestMeasure.setText("");
			}
					
					
			if (DocLine.ordervalue > 0) {
				holder.DocOrder.setText(String.valueOf(DocLine.ordervalue));			
				holder.DocOrderSum.setText(String.format("=%.2f ", DocLine.order_sum));				
			}
			else
			{
				holder.DocOrder.setText("");
				holder.DocOrderSum.setText("");
				holder.DocOrderMeasure.setText("");
			}
			
			if (CustomerAssortment){
				holder.GoodsDescr.setTextColor(Color.rgb(0xff, 0x8c, 0x00));
			}					

			if (TOPAssortment){
				holder.GoodsDescr.setTextColor(Color.RED);
			}		
			
			String AddString = DocumentClass.DocLineAddCollectionLineString (DocLine.id); 
			
			if (AddString==null){
				holder.OrdeGoodAddtextView.setVisibility(View.GONE);	
			}
			else
			{
				holder.OrdeGoodAddtextView.setVisibility(View.VISIBLE);
				holder.OrdeGoodAddtextView.setText(AddString);
			}
			
			
			if (!(OffersGoodsList==null)) {
				if (OffersGoodsList.contains(gi.id)) {
					holder.GoodsDescr.setTextColor(Color.MAGENTA);
				}
			}
			
			return convertView;
		
		}
		 
		class ViewHolder {
			
			TextView GoodsDescr;
			TextView GoodsRest;			
			
			TextView DocPrice;
			
			TextView DocRest;
			TextView DocOrder;
			
			TextView DocOrderMeasure;
			TextView DocRestMeasure;			
			
			TextView DocRestSum;
			TextView DocOrderSum;
			
			TextView OrdeGoodAddtextView;
			
		}
		 
				 
		@Override
		public long getItemId(int position) {
			
			return 0;
			
		}
		 
		@Override
		public int getCount() {
			
			return GoodsRef.size();
			
		}
		 
		@Override
		public GoodsRefItem getItem(int position) {
			
			return GoodsRef.get(position);
			
		}
	
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    				
    			setResult(RESULT_CANCELED);
    			finish();	
    		
    	}	
		
		return super.onKeyDown(keyCode, event);
	}	
	
}
